/**
 * 函数作用:
 * KVOB.stringify:将{str:"字符串",level:"99"}转为字符串=>?str=%E5%AD%97%E7%AC%A6%E4%B8%B2&level=99
 * KVOB.parse:将?str=%E5%AD%97%E7%AC%A6%E4%B8%B2&level=99转为{str:"字符串",level:"99"}
 */

//#region 工具函数
function getDataType(val) {//判断数据类型
  return Object.prototype.toString.call(val);
}
function judgeStrIncludeObject(str) {//判断字符串中是否包含"object"
  return str.includes("object");
}
function objChangeToStr(obj) {//对象类型转字符串类型
  return new URLSearchParams(obj).toString();
}
//#endregion

let KVOB = {};
KVOB.instructions=function(){
  console.log(`
    函数作用:
      KVOB.stringify:将{str:"字符串",level:"99"}转为字符串=>?str=%E5%AD%97%E7%AC%A6%E4%B8%B2&level=99
      KVOB.parse:将?str=%E5%AD%97%E7%AC%A6%E4%B8%B2&level=99转为{str:"字符串",level:"99"}
  `)
}

KVOB.parse = function (str) {
  switch (getDataType(str)) {
    case "[object String]":
      if (judgeStrIncludeObject(str)) {
        return new Error("您输入的字符串包含object,无法正常解析...");
      } else {
        let obj = {};
        new URLSearchParams(str).forEach((item, index) => {
          obj[index] = item;
        });
        return obj;
      }
    default:
      return new Error("您输入的不是字符串,输入字符串...");
  }
};
KVOB.parse.instructions=function(){
  console.log(`
    1.形参类型:字符串,  
    2.返回值:{}
  `)
}

KVOB.stringify = function (obj) {
  switch (getDataType(obj)) {
    case "[object Object]":
      let str = objChangeToStr(obj);
      if (judgeStrIncludeObject(str)) {
        return new Error(
          "您输入的对象包含object,无法正常解析,KVOB.stringify.instructions()来查看正确输入格式"
        );
      } else {
        return '?'+new URLSearchParams(obj).toString();
      }

    default:
      return new Error("您输入的不是对象格式,输入对象格式...");
  }
};
KVOB.stringify.instructions=function(){
  console.log(`
    1.形参类型:{}
      1.1{}中value的值不能是{}
      1.2{}中value的值最好都是字符串,如果是数字/布尔/null/undefined会被转成字符串
      1.3{}中的value的值是数组(数组会被扁平化处理),数组中的值不能是{},最好都是字符串,如果是数字/布尔会被转成字符串,如果是null/undefined会被转成空
      1.4{}中value的值-示例
      {
        str: "张三",
        num: "1",
        bool:"true",
        sd:"null",
        s:"undefined",
        arr:["李四", "12", "false","undefined","null"]
      }
      1.5总而言之就一句话-{}中value的值最好都是字符串！！！
    2.返回值:字符串
      2.1返回值-示例
      ?name=%E5%BC%A0%E4%B8%89&age=12&bool=true&sd=null&s=undefined&arr=%E6%9D%8E%E5%9B%9B%2C12%2Cfalse%2C%2C
  `)
}

export {
  KVOB
};